﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Arthas.Controls.Metro;
using Arthas.Utility.Media;
using System.Reflection;
using System.Windows.Threading;
using System.Data;
using InteractiveDataDisplay.WPF;
using System.IO;
using Microsoft.Win32;
using Excel;
using System.Windows.Controls.Primitives;
using Microsoft.Expression.Shapes;
using Arc = Microsoft.Expression.Shapes.Arc;
using ChatServer;
using Thedog;
using NotificationDemoWPF;
using RDLCPrinter;
using Microsoft.Reporting.WinForms;

namespace ELM
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        public Encoding OutputEncoding { get; private set; }

        public MainWindow()
        {
            //string ss = "826291057.";
            //string one=Md5.CreateMd5(s);
            //string two = Md5.CreateMd5(one);
            //MessageBox.Show(one);
            //MessageBox.Show(two);

            //int a = 1;   for不常见用法
            //bool b = true;
            //if (a == 20) { b = false; }
            //for (; b; a++)
            //{
            //    if (a == 2) { MessageBox.Show("2"); }
            //    if (a==10) { MessageBox.Show("10"); }
            //    if (a == 20) { MessageBox.Show("20"); }
            //    if (a == 30) { MessageBox.Show("20"); }
            //}
            //string words = "1,2.3,4";
            //string[] split = words.Split(new Char[] { ',' });//返回:{"1","2.3","","4"}
            InitializeComponent();
            //把Close()委托到退出按钮
            Exit.Click += delegate { Close(); };
            #region 库存视图总页数
            SPageNumber.Title = "共有" + Bridge.PageCount.ToString() + "页";
            IPageNumber.Title = "共有" + Bridge.PageCount.ToString() + "页";
            OPageNumber.Title = "共有" + Bridge.PageCount.ToString() + "页";
            Bridge.UsuallyPageCount();
            DeliverRecord_IPageNumber.Title = "共有" + Bridge.usuallyPageCount[0].ToString() + "页";
            #endregion
            #region 显示视图
            //显示四个库存操作所需的表
            StockManage.GoodsSelect(this);
            //显示三个运输工具管理操作所需表
            TransportManagement.TransportSelect(this);
            //显示三个订单管理操作所需视图
            OrderManagement.OrderSelect(this);
            //显示记录管理操作所需试图
            TransactionRecordManagement.TransactionRecordSelect(this);
            //显示客户管理操作所需试图
            CustomerManagement.CustomerSelect(this);
            //显示资金管理五个视图
            CapitalManagement.CapitalSelect(this);
            //显示出货记录的三个视图
            DeliverRecord.DeliverSelect(this);
            #endregion
            //加载内部页面和浏览器定向到外部页面
            web2.Source = new Uri(@"C:\Users\黄燕槟\Desktop\ELM\ELM\Resources\ChargingManagement.html"); //new Uri("https://www.baidu.com/s?wd=1");
            #region 以前做的注释掉了
            // ContentRendered += delegate
            //{
            //    // 手动加载指定HTML Assembly:程序集     Assembly GetExecutingAssembly获得当前程序的绝对路径
            //    //web1.Document = ResObj.GetString(Assembly.GetExecutingAssembly(), "Resources.about.html");//得不到正确路径还不知道准确原因 很可能是获取的绝对路径格式不对
            //   web1.Navigate(@"C:\Users\黄燕槟\Desktop\ELM\ELM\Resources\about.html");
            //    // 导航到指定网页
            //    //web2.Source = new Uri("http://ie.icoa.cn/");
            //   // web2.Source = new Uri("https://map.baidu.com/");
            //};
            #endregion
            //Expanded的初始化
            foreach (FrameworkElement fe in lists.Children)
            {
                if (fe is MetroExpander)
                {
                    (fe as MetroExpander).Click += delegate (object sender, EventArgs e)
                    {
                        if ((fe as MetroExpander).CanHide)
                        {
                            foreach (FrameworkElement fe1 in lists.Children)
                            {
                                if (fe1 is MetroExpander && fe1 != sender)
                                {
                                    (fe1 as MetroExpander).IsExpanded = false;
                                }
                            }
                        }
                    };
                }
            }
            #region 图表
            //数量-生产日期柱状图
            //输出参数载体
            double[] s = new double[5];
            double[] s1 = new double[5];
            double[] s2 = new double[5];
            double[] s3 = new double[5];
            s=DataAnalysis.GetChartData(out s1, out s2, out s3);

            //string ss = "";
            //for (int i = 0; i < 5; i++)
            //{
                
            //    ss = ss + s[i].ToString() + s1[i].ToString() + s2[i].ToString() + s3[i].ToString()+"//";
             
            //}
            //MessageBox.Show(ss);

            //y轴的拉大导致画出来的过细甚至看不见 目前找不到解决方法
            //int N = 100;
            //double[] y = new double[N];
            //double[] y11 = new double[N];
            //Random r = new Random();
            //double k;
            //double k11;

            //for (int i = 0; i < N; i++)
            //{
            //    k = r.NextDouble();
            //    k11 = r.NextDouble();
            //    y[i] = k < 0.5 ? r.Next(100) : -r.Next(100);
            //    y11[i] = k11< 0.5 ? r.Next(100) : -r.Next(100);
            //}
           //barChart_1_Histogram.PlotBars(y);
            barChart_1_Histogram.Plot(s1,s);
            barChart_1_Histogram.BarsWidth = 10;//画出来的柱状图的宽 默认就为1
            //数量-生产日期曲线图
            //double[] x = new double[200];
            //for (int i = 0; i < x.Length; i++)
            //    x[i] = 3.1415 * i / (x.Length - 1);


                var lg = new LineGraph();
                lines.Children.Add(lg);
                lg.Stroke = new SolidColorBrush(Color.FromArgb(255, 0, (byte)0, 0));
                lg.Description = String.Format("Data series {0}",1);
                lg.StrokeThickness = 2;
                lg.Plot(s1,s);  //参数一样两个数组？ =>左边变量带入到右边表达式
            

            //剩余容量-数量柱状图
            //int N1 = 100;
            //double[] y1 = new double[N1];
            ////用同一个ramdom用再new一个会导致数据都一样 具体原因不确定
            ////Random r1 = new Random();
            //double k1;

            //for (int i = 0; i < N1; i++)
            //{
            //    //y1[i] = i;
            //    k1 = r.NextDouble();
            //    y1[i] = k1 < 0.5 ? r.Next(100) : -r.Next(100);
            //}
            //BarChart_2_Histogram.PlotBars(y1);
            BarChart_2_Histogram.Plot(s3,s2);
            BarChart_2_Histogram.BarsWidth = 250;
            //订单图表
            double[] s4 = new double[4];
            double[] s5 = new double[4];
            s4 = OrderDataAnalysis.GetChartData(out s5);
            //订单数-季度柱
            BarChart_3_Histogram.Plot(s5, s4);
            BarChart_3_Histogram.BarsWidth = 0.2;
            //订单数-季度曲
            var lg1 = new LineGraph();
                lines1.Children.Add(lg1);
                lg1.Stroke = new SolidColorBrush(Color.FromArgb(255, 0, (byte)0, 0));
                lg1.Description = String.Format("Data series {0}",1);
                lg1.StrokeThickness = 2;
                lg1.Plot(s5, s4);  //参数一样两个数组？ =>左边变量带入到右边表达式
            #endregion
            #region 数据统计
            string[] countData = OrderDataAnalysis.GetCountData();
            FristOrder.Text = "第一单："+countData[0]+"时间："+countData[1];
           LastOrder.Text = "最后一单：" + countData[2] + "时间：" + countData[3];
            MaxPay.Text = "最大单："+countData[4]+"金额："+countData[5];
           MinPay.Text= "最小单：" + countData[6] + "金额：" + countData[7];
            CountMoney.Text = "累计金额：" + countData[9];
            CountOrders.Text = "累计订单：" + countData[8];
            #endregion
            //权限限制 OrderM.Visibility = Visibility.Collapsed;  TransportM  StockM  TransactionRecordM CustomerM ChargingM MoneyM 存在bug侧边选择仍然可以调出界面不想改
            switch (Bridge.Position)
            {
                case "管理员":MessageBox.Show("可爱的管理员，欢迎您"); break;
                case "客服":TransportS.Visibility = Visibility.Collapsed; TransportI.Visibility = Visibility.Collapsed; TransportU.Visibility = Visibility.Collapsed;
                    MoneyM.Visibility = Visibility.Collapsed; OrderM.Visibility = Visibility.Collapsed; StockM.Visibility = Visibility.Collapsed; CustomerM.Visibility = Visibility.Collapsed; MessageBox.Show("可爱的客服，欢迎您"); break;
                case "业务员": MoneyM.Visibility = Visibility.Collapsed; StockM.Visibility = Visibility.Collapsed; TransportM.Visibility = Visibility.Collapsed; ChargingM.Visibility = Visibility.Collapsed; MessageBox.Show("可爱的业务员，欢迎您"); break;
                case "运输管理员": MoneyM.Visibility = Visibility.Collapsed; OrderM.Visibility = Visibility.Collapsed; StockM.Visibility = Visibility.Collapsed; TransactionRecordM.Visibility = Visibility.Collapsed; CustomerM.Visibility = Visibility.Collapsed; ChargingM.Visibility = Visibility.Collapsed; MessageBox.Show("可爱的运管，欢迎您"); break;
                case "仓库管理员": MoneyM.Visibility = Visibility.Collapsed; OrderM.Visibility = Visibility.Collapsed; TransportM.Visibility = Visibility.Collapsed; TransactionRecordM.Visibility = Visibility.Collapsed; CustomerM.Visibility = Visibility.Collapsed; ChargingM.Visibility = Visibility.Collapsed; MessageBox.Show("可爱的仓管，欢迎您"); break;
                case "会计": OrderI.Visibility = Visibility.Collapsed; OrderU.Visibility = Visibility.Collapsed;
                    TransportM.Visibility = Visibility.Collapsed; CustomerM.Visibility = Visibility.Collapsed; StockM.Visibility = Visibility.Collapsed; MessageBox.Show("可爱的会计，欢迎您"); break;
                default: break; //MessageBox.Show("无权访问！"); this.Close();调试先允许使用
            }
        }
        #region 切换视图部分
        private void MetroExpander_Click_Select(object sender, EventArgs e)
        {
            Select.IsSelected = true;
        }
        private void MetroExpander_Click_StockIn(object sender, EventArgs e)
        {
            StockIn.IsSelected = true;
        }
        private void MetroExpander_Click_StockOut(object sender, EventArgs e)
        {
            StockOut.IsSelected = true;
        }
        private void MetroExpander_Click_Chart(object sender, EventArgs e)
        {
            Chart.IsSelected = true;
        }
        private void MetroExpander_Click_BigData(object sender, EventArgs e)
        {
            BigData.IsSelected = true;
        }
        #endregion
        //查询_上一页
        private void SPMetroButton_Click(object sender, RoutedEventArgs e)
        {
            SDataShow.ItemsSource = StockManage.PreviousPage(this).DefaultView;
        }
        //入库_上一页
        private void IPMetroButton_Click(object sender, RoutedEventArgs e)
        {
            IDataShow.ItemsSource = StockManage.PreviousPage(this).DefaultView;
        }
        //出_库上一页
        private void OPMetroButton_Click(object sender, RoutedEventArgs e)
        {
            ODataShow.ItemsSource = StockManage.PreviousPage(this).DefaultView;
        }
        //查询_下一页
        private void SNMetroButton_Click(object sender, RoutedEventArgs e)
        {
            SDataShow.ItemsSource = StockManage.NextPage(this).DefaultView;
        }
        //入库_下一页
        private void INMetroButton_Click(object sender, RoutedEventArgs e)
        {
            IDataShow.ItemsSource = StockManage.NextPage(this).DefaultView;
        }
        //出库_下一页
        private void ONMetroButton_Click(object sender, RoutedEventArgs e)
        {
            ODataShow.ItemsSource = StockManage.NextPage(this).DefaultView;
        }
        //查询_跳页
        private void SSMetroButton_Click(object sender, RoutedEventArgs e)
        {
            SDataShow.ItemsSource = StockManage.SkipPage(this).DefaultView;
        }
        //入库_跳页
        private void ISMetroButton_Click(object sender, RoutedEventArgs e)
        {
            IDataShow.ItemsSource = StockManage.SkipPage(this).DefaultView;
        }
        //出库_跳页
        private void OSMetroButton_Click(object sender, RoutedEventArgs e)
        {

            ODataShow.ItemsSource = StockManage.SkipPage(this).DefaultView;

        }

        private void MetroButton_Click(object sender, RoutedEventArgs e)
        {
            SGoodsId.Text = "";
            SGoodsName.Text = "";
        }
        //库存管理条件搜索
        private void SExactly_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            //封装到StockMangge里去了 先不删  以免思想出问题
            //string goodsId = SGoodsId.Text;
            //string goodsName = SGoodsName.Text;
            //DataTable s = new DataTable();
            //string sCondition = String.Format(" where Goods_Id='{0}'", goodsId);
            //if (goodsId == "" && goodsName == "")
            //{
            //    MessageBox.Show("二者至少有一个要有数据");
            //}
            //else
            //{
            //    if (goodsId == "")
            //    {
            //        sCondition = String.Format(" where Goods_Name='{0}'", goodsName);
            //    }
            //    string sqlcommand = String.Format("select * from Goods {0}", sCondition);
            //    s = DataAccess.GetResult(sqlcommand);
            //}
            System.Data.DataTable s = StockManage.SelectExactly(this);
            if (s.Rows.Count == 0)
            {

            }
            else
            {
                SDataShow.ItemsSource = s.DefaultView;
            }
            //return s;

        }

        private void MetroButton_Click_1(object sender, RoutedEventArgs e)
        {
            SW_Start.Text = "";
            SW_End.Text = "";
            SS_Start.Text = "";
            SS_End.Text = "";
            SD_Start.Text = "";
            SD_End.Text = "";
            SL_Start.Text = "";
            SL_End.Text = "";
        }

        private void MetroButton_Click_2(object sender, RoutedEventArgs e)
        {
            IGoodsId.Text = "";
            IGoodsName.Text = "";
            IWarehouseId.Text = "";
            IStock.Text = "";
            IDateOfManufacture.Text = "";
            IShelfLife.Text = "";
            IStockPlus.Text = "";
        }

        private void MetroButton_Click_3(object sender, RoutedEventArgs e)
        {
            OGoodsId.Text = "";
            OGoodsName.Text = "";
            OWarehouseId.Text = "";
            OStock.Text = "";
            ODateOfManufacture.Text = "";
            OShelfLife.Text = "";
            OStockReduce.Text = "";
        }
        //库存管理条件搜索
        private void SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            //返回数组为空则维持原样
            System.Data.DataTable s = StockManage.SelectByCondition(this);
            if (s.Rows.Count == 0)
            {

            }
            else
            {
                SDataShow.ItemsSource = s.DefaultView;
            }
        }
        //库存+1
        private void Stock_In_Plus1_Button_Click(object sender, RoutedEventArgs e)
        {
            //获取第一列当前单元格的值
            //string result = (IDataShow.Columns[0].GetCellContent(IDataShow.CurrentCell.Item) as TextBlock).Text;
            //MessageBox.Show(result);
            string iGoodsId;
            DataRowView dr = IDataShow.SelectedItem as DataRowView;
            if (dr != null)
            {
                iGoodsId = dr["货物编码"].ToString();
                StockManage.StockOperation(iGoodsId, "+=1");
                //调用跳页刷新当前页
                //返回数组为空则维持原样
                System.Data.DataTable s = StockManage.RefreshSkipPage(this);
                if (s.Rows.Count == 0)
                {

                }
                else
                {
                    IDataShow.ItemsSource = s.DefaultView;
                }
            }
        }
        //入库下选中数据和对应METRO:TEXTBOX传值
        private void IDataShow_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            DataRowView dr = IDataShow.SelectedItem as DataRowView;
            if (dr != null)
            {
                IGoodsId.Text = dr["货物编码"].ToString();
                IGoodsName.Text = dr["货物名"].ToString();
                IWarehouseId.Text = dr["仓库号"].ToString();
                IStock.Text = dr["库存"].ToString();
                IDateOfManufacture.Text = dr["生产日期"].ToString();
                IShelfLife.Text = dr["保质期"].ToString();
                //time.SelectedDate = DateTime.Parse(dr["测试日期"].ToString());
            }
        }
        //出库下的更新
        private void Stock_Out_Update_Insert_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            string oGoodsId = OGoodsId.Text;
            string oGoodsName = OGoodsName.Text;
            string oWarehouseId = OWarehouseId.Text;
            string oStock = OStock.Text;
            string oDateOfManufacture = ODateOfManufacture.Text;
            string oShelfLife = OShelfLife.Text;
            string oStockReduce = OStockReduce.Text;
            StockManage.Stock_O_I_C_I(this, oGoodsId, oGoodsName, oWarehouseId, oStock, oDateOfManufacture, oShelfLife, oStockReduce);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("Goods", "Goods_Id", this.OPageNumber);
            ODataShow.ItemsSource = Stock_TableHeadHandle(s).DefaultView;
        }
        //入库下的更新
        private void Stock_In_Update_Insert_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            string iGoodsId = IGoodsId.Text;
            string iGoodsName = IGoodsName.Text;
            string iWarehouseId = IWarehouseId.Text;
            string iStock = IStock.Text;
            string iDateOfManufacture = IDateOfManufacture.Text;
            string iShelfLife = IShelfLife.Text;
            string iStockPlus = IStockPlus.Text;
            StockManage.Stock_O_I_C_I(this, iGoodsId, iGoodsName, iWarehouseId, iStock, iDateOfManufacture, iShelfLife, iStockPlus);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("Goods", "Goods_Id", this.IPageNumber);
            IDataShow.ItemsSource = Stock_TableHeadHandle(s).DefaultView;
        }
        //库存-1
        private void Stock_Out_Reduce1_Button_Click(object sender, RoutedEventArgs e)
        {
            string iGoodsId;
            DataRowView dr = ODataShow.SelectedItem as DataRowView;
            if (dr != null)
            {
                iGoodsId = dr["货物编码"].ToString();
                StockManage.StockOperation(iGoodsId, "-=1");
                //调用跳页刷新当前页
                //返回数组为空则维持原样
                System.Data.DataTable s = StockManage.RefreshSkipPage(this);
                if (s.Rows.Count == 0)
                {

                }
                else
                {
                    ODataShow.ItemsSource = s.DefaultView;
                }
            }
        }
        //库存归零
        private void Stock_Out_Zeroing_Button_Click(object sender, RoutedEventArgs e)
        {

            string iGoodsId;
            DataRowView dr = ODataShow.SelectedItem as DataRowView;
            if (dr != null)
            {
                iGoodsId = dr["货物编码"].ToString();
                StockManage.StockOperation(iGoodsId, "=0");
                //调用跳页刷新当前页
                //返回数组为空则维持原样
                System.Data.DataTable s = StockManage.RefreshSkipPage(this);
                if (s.Rows.Count == 0)
                {

                }
                else
                {
                    ODataShow.ItemsSource = s.DefaultView;
                }
            }
        }
        //官网点击
        private void OfficialWebsite_MetroMenuItem_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://blog.csdn.net/weixin_44231544");
        }
        //大数据计算
        private void BigData_MetroButton_Click_4(object sender, RoutedEventArgs e)
        {
            pb.Value = 0;
            pb.Title = "正在计算：";
            string b_GoodsId = B_GoodsId.Text;
            string b_ShelfLife = B_ShelfLife.Text;
            string b_Stock = B_Stock.Text;
            if (b_GoodsId == "" || b_ShelfLife == "" || b_Stock == "")
            {
                MessageBox.Show("请填充完整的数据");
            }
            else
            {
                List<EasyGoods> sampleList = DataAnalysis.GetEasyGoodsDataset(AppDomain.CurrentDomain.BaseDirectory + "样本放在Debug目录下.txt");
                List<EasyGoods> unclassifyList = new List<EasyGoods>();
                EasyGoods easyGoods = new EasyGoods();
                easyGoods.ShelfLife = Convert.ToDouble(b_ShelfLife);
                easyGoods.Stock = Convert.ToDouble(b_Stock);
                easyGoods.Strategy = "";
                unclassifyList.Add(easyGoods);
                //最近两个邻居
                KNN tool = new KNN(sampleList, unclassifyList, 2);
                tool.Classify();
                DispatcherTimer timer = new DispatcherTimer();
                pb.Title = "正在计算：";
                timer.Tick += delegate
                {
                    pb.Value = pb.Value + 1 > pb.Maximum ? 100: pb.Value + 1;
                    pb.Hint = null;
                    if (pb.Value == 100)
                    {
                        pb.Title = "结果为：";
                        rt3.AddLine("货物编号为:");
                        rt3.AddLine(b_GoodsId, new RgbaColor(255, 0, 0, 255), delegate { MessageBox.Show("别碰我，咱害羞~"); });
                        rt3.AddLine("的货物推荐采用：", new RgbaColor(0, 255, 0, 255));
                        rt3.AddLine(Bridge.AnalysisResult, new RgbaColor(0, 0, 255, 255), delegate { MessageBox.Show("别碰我，咱害羞~"); });
                        timer.Stop();//正航
                        //写入样本按钮打开
                        if (IsWrite.IsChecked == true)
                        {             
                            string temp = Bridge.AnalysisResult;
                            //MessageBox.Show(temp.Substring(1, temp.Length-2 ));
                            //写入样本
                            FileStream fs = new FileStream(@"C:\Users\黄燕槟\Desktop\ELM\ELM\bin\Debug\样本放在Debug目录下.txt", FileMode.Append);
                            StreamWriter wr = null;
                            wr = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));//防止乱码
                            wr.WriteLine("\"" + b_GoodsId + "\"" + " " + b_ShelfLife + " " + b_Stock + " " + "\"" + temp.Substring(1, temp.Length - 2) + "\"");
                            wr.Close();
                        }
                    }
                };
                timer.Interval = new TimeSpan(0, 0, 0, 0, 1);
                timer.Start();
            }
        }

        private void MetroButton_Click_4(object sender, RoutedEventArgs e)
        {
            STool_Id.Text = "";
            STool_Type.Text = "";
        }

        //工具管理下准确查询
        private void Transport_SExactly_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = TransportManagement.SelectExactly(this);
            SDataShow1.ItemsSource = S.DefaultView;
        }

        private void MetroButton_Click_5(object sender, RoutedEventArgs e)
        {
            ITool_Id.Text = "";
            ITool_Type.Text = "";
            IDriver.Text = "";
            IIs_Free.Text = "";
            IEndurance.Text = "";
            IFuel_Type.Text = "";
            IDeadweight.Text = "";
        }

        private void MetroButton_Click_6(object sender, RoutedEventArgs e)
        {
            UTool_Id.Text = "";
            UTool_Type.Text = "";
            UDriver.Text = "";
            UIs_Free.Text = "";
            UEndurance.Text = "";
            UFuel_Type.Text = "";
            UDeadweight.Text = "";
        }

        //工具管理下插入
        private void Transport_Insert_MetroButton_Click(object sender, RoutedEventArgs e)
        {
                TransportManagement.Transport_Insert(this);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("Conveyance", "Tool_Id", this.ToolCreate_PageNumber);
            IDataShow1.ItemsSource = Transport_TableHeadHandle(s).DefaultView;
        }
        //工具管理下更新
        private void Transport_Update_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            TransportManagement.Transport_Update(this);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("Conveyance", "Tool_Id", this.ToolUpdata_PageNumber);
            UDataShow1.ItemsSource = Transport_TableHeadHandle(s).DefaultView;
        }

        private void MetroButton_Click_7(object sender, RoutedEventArgs e)
        {
            SOrder_Id.Text = "";
            SCustomer_Id.Text = "";
      }

        private void MetroButton_Click_8(object sender, RoutedEventArgs e)
        {
            IOrder_Id.Text = "";
            ICreate_DateTime.Text = "";
            ICustomer_Id.Text = "";
            ICustomer_Name.Text = "";
            ICustomer_Tel.Text = "";
            IPlace_Of_Delivery.Text = "";
            IDestination.Text = "";
            IGoods.Text = "";
            INumber.Text = "";
            IOrder_State.Text = "";
        }

        private void MetroButton_Click_9(object sender, RoutedEventArgs e)
        {
            UOrder_Id.Text = "";
            UCreate_DateTime.Text = "";
            UCustomer_Id.Text = "";
            UCustomer_Name.Text = "";
            UCustomer_Tel.Text = "";
            UPlace_Of_Delivery.Text = "";
            UDestination.Text = "";
            UGoods.Text = "";
            UNumber.Text = "";
            UOrder_State.Text = "";
        }
        //订单管理下准确查询
        private void Order_SExactly_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S =OrderManagement.SelectExactly(this);
            SDataShow2.ItemsSource = S.DefaultView;
        }
        //订单管理下修改
        private void Order_Update_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            OrderManagement.Order_Update(this);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("FormalOrder", "Order_Id", this.OrderUpdata_PageNumber);
            UDataShow2.ItemsSource = Order_TableHeadHandle(s).DefaultView;
        }
        #region 订单插入模拟通知
        //订单插入模拟通知相关
        public static List<NotificationWindow> _dialogs = new List<NotificationWindow>();
        private void Dialog_Closed(object sender, EventArgs e)
        {
            var closedDialog = sender as NotificationWindow;
            _dialogs.Remove(closedDialog);
        }
        double GetTopFrom()
        {
            //屏幕的高度-底部TaskBar的高度。
            double topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 10;
            bool isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);

            while (isContinueFind)
            {
                topFrom = topFrom - 110;//此处100是NotifyWindow的高 110-100剩下的10  是通知之间的间距
                isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);
            }

            if (topFrom <= 0)
                topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 10;

            return topFrom;
        }
        #endregion
        //订单管理下插入
        private void Order_Insert_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            NotifyData data = new NotifyData();
            data.Title = "新增需要出库的订单！";
            data.Content = "订单号："+ IOrder_Id.Text;
            OrderManagement.Order_Insert(this);

            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("FormalOrder", "Order_Id", this.OrderInsert_PageNumber);
            IDataShow2.ItemsSource = Order_TableHeadHandle(s).DefaultView;

            NotificationWindow dialog = new NotificationWindow();//new 一个通知
            dialog.Closed += Dialog_Closed;
            dialog.TopFrom = GetTopFrom();
            _dialogs.Add(dialog);
            dialog.DataContext = data;//设置通知里要显示的数据
            dialog.Show();
        }

        private void MetroButton_Click_10(object sender, RoutedEventArgs e)
        {
            SFormal_Order_Id.Text = "";
            SRecord.Text = "";
        }
        //交易记录准确查询
        private void TransactionRecord_SExactly_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = TransactionRecordManagement.SelectExactly(this);
           DataShow_TransactionRecord.ItemsSource = S.DefaultView;
        }

        //运输实时跟踪点击
        private void TransportationTracking_MetroTabItem_GotFocus(object sender, RoutedEventArgs e)
        {
                //加载内部页面和浏览器定向到外部页面
                web1.Navigate(@"C:\Users\黄燕槟\Desktop\ELM\ELM\Resources\about.html");
         }

        private void MetroButton_Click_11(object sender, RoutedEventArgs e)
        {
            SCustomerId.Text = "";
            SCustomerTel.Text = "";
        }
        //客户准确查询
        private void Customer_SExactly_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = CustomerManagement.SelectExactly(this);
            SDataShow_Customer.ItemsSource = S.DefaultView;
        }

        private void MetroButton_Click_12(object sender, RoutedEventArgs e)
        {
            UCustomerId.Text = "";
            UCustomerName.Text = "";
            UCustomerSex.Text = "";
            UCustomerTel.Text = "";
            UEmployee_Id.Text = "";
        }
        //客户修改
        private void Customer_Update_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            CustomerManagement.Customer_Update(this);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("Customer", "Customer_Id", this.CustormerUpdata_PageNumber);
            UDataShow_Customer.ItemsSource = Custormer_TableHeadHandle(s).DefaultView;
        }
        #region 视图切换
        private void MetroExpander_Click(object sender, EventArgs e)
        {
            TransportS.IsSelected = true;
        }

        private void MetroExpander_Click_1(object sender, EventArgs e)
        {
            TransportI.IsSelected = true;
        }

        private void MetroExpander_Click_2(object sender, EventArgs e)
        {
            TransportU.IsSelected = true;
        }
        #endregion
        //运输实时跟踪点击时focus
        private void MetroExpander_Click_3(object sender, EventArgs e)
        {
            //TransportPursue.IsSelected = true;
            TransportPursue.Focus();
        }
        #region 视图切换
        private void MetroExpander_Click_4(object sender, EventArgs e)
        {
            OrderS.IsSelected = true;
        }

        private void MetroExpander_Click_5(object sender, EventArgs e)
        {
            OrderI.IsSelected = true;
        }

        private void MetroExpander_Click_6(object sender, EventArgs e)
        {
            OrderU.IsSelected = true;
        }

        private void MetroExpander_Click_7(object sender, EventArgs e)
        {
            OrderChart.IsSelected = true;
        }

        private void MetroExpander_Click_8(object sender, EventArgs e)
        {
            OrderDataCount.IsSelected = true;
        }

        private void MetroExpander_Click_9(object sender, EventArgs e)
        {
            CustomerS.IsSelected = true;
        }

        private void MetroExpander_Click_10(object sender, EventArgs e)
        {
            CustomerU.IsSelected = true;
        }
#endregion
        //点击登出
        private void Logout_MetroMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Login s = new Login();
            s.Show();
            this.Close();
        }
        //离开锁定
        private void LeaveLock_MetroMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var win = new LeaveLock(); 
            win.Owner = this; // 设置其所有者
                              // 设置窗口启动时的定位为所有者中心位置
            win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            win.ShowDialog(); // 显示模式窗口，即直到窗口被关闭，才能对其他窗口进行操作
        }

        private void MetroButton_Click_13(object sender, RoutedEventArgs e)
        {
            Customer_Sex.Text = "";
            Employee_Id.Text = "";
        }

        //客户条件查询调用
        private void Customer_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S =CustomerManagement.SelectByCondition(this);
            SDataShow_Customer.ItemsSource = S.DefaultView;
        }

        private void MetroButton_Click_14(object sender, RoutedEventArgs e)
        {
            Place_Of_Delivery.Text = "";
            Destination.Text = "";
            Goods.Text = "";
            Order_State.Text = "";
            Create_DateTime_Start.Text = "";
            Create_DateTime_End.Text = "";
        }
        //订单条件查询
        private void Order_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = OrderManagement.SelectByCondition(this);
            SDataShow2.ItemsSource = S.DefaultView;
        }

        private void MetroButton_Click_15(object sender, RoutedEventArgs e)
        {
            Tool_Type.Text = "";
            Is_Free.Text = "";
            Fuel_Type.Text = "";
            Endurance_Start.Text = "";
            Endurance_End.Text = "";
            Deadweight_Start.Text = "";
            Deadweight_End.Text = "";
        }
        //运输条件查询
        private void Conveyance_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = TransportManagement.SelectByCondition(this);
            SDataShow1.ItemsSource = S.DefaultView;
        }

        private void MetroButton_Click_16(object sender, RoutedEventArgs e)
        {
            Pay_State.Text = "";
            PaymentAmount_Start.Text = "";
            PaymentAmount_End.Text = "";
            Creation_DateTime_Start.Text = "";
            Creation_DateTime_End.Text = "";
            Over_DateTime_Start.Text = "";
            Over_DateTime_End.Text = "";
        }
        //交易记录条件查询
        private void TransactionRecord_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = TransactionRecordManagement.SelectByCondition(this);
            DataShow_TransactionRecord.ItemsSource = S.DefaultView;
        }

        private void MetroButton_Click_17(object sender, RoutedEventArgs e)
        {
            TapOne_Currency_Type.Text = "";
            TapOne_Total_Start.Text = "";
            TapOne_Total_End.Text = "";
        }

        private void MetroButton_Click_18(object sender, RoutedEventArgs e)
        {
            TapTwo_Currency_Type.Text = "";
            TapTwo_PartyA.Text = "";
            TapTwo_Fun_Start.Text = "";
            TapTwo_Fun_End.Text = "";
            TapTwo_AppointedDate_Start.Text = "";
            TapTwo_AppointedDate_End.Text = "";
        }

        private void MetroButton_Click_19(object sender, RoutedEventArgs e)
        {
            TapThree_Currency_Type.Text = "";
            TapThree_PartyB.Text = "";
            TapThree_Fun_Start.Text = "";
            TapThree_Fun_End.Text = "";
            TapThree_AppointedDate_Start.Text = "";
            TapThree_AppointedDate_End.Text = "";
        }

        private void MetroButton_Click_20(object sender, RoutedEventArgs e)
        {
            TapFour_Currency_Type.Text = "";
            TapFour_PartyA.Text = "";
            TapFour_Fun_Start.Text = "";
            TapFour_Fun_End.Text = "";
            TapFour_PayDate_Start.Text = "";
            TapFour_PayDate_End.Text = "";
        }

        private void MetroButton_Click_21(object sender, RoutedEventArgs e)
        {
            TapFive_Currency_Type.Text = "";
            TapFive_PartyB.Text = "";
            TapFive_Fun_Start.Text = "";
            TapFive_Fun_End.Text = "";
            TapFive_PaymentDate_Start.Text = "";
            TapFive_PaymentDate_End.Text = "";
        }
        //资金管理资金汇总条件查询
        private void MoneyM_TapOne_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = CapitalManagement.Capital_SelectByCondition(this);
            DataShow_Capital.ItemsSource = S.DefaultView;
        }
        //资金管理未收款项条件查询
        private void MoneyM_TapTwo_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = CapitalManagement.NoReceivables_SelectByCondition(this);
            DataShow_NoReceivable.ItemsSource = S.DefaultView;
        }
        //资金管理未支款项条件查询
        private void MoneyM_TapThree_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = CapitalManagement.NoPay_SelectByCondition(this);
            DataShow_NoPay.ItemsSource = S.DefaultView;
        }
        //资金管理已支款项条件查询
        private void MoneyM_TapFour_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = CapitalManagement.HadPay_SelectByCondition(this);
            DataShow_HadPay.ItemsSource = S.DefaultView;
        }
        //资金管理已收款项条件查询
        private void MoneyM_TapFive_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = CapitalManagement.HadReceivables_SelectByCondition(this);
            DataShow_HadReceivable.ItemsSource = S.DefaultView;
        }
        #region 试图切换
        private void MetroExpander_Click_11(object sender, EventArgs e)
        {
            SelectRecord.IsSelected = true;
        }

        private void MetroExpander_Click_12(object sender, EventArgs e)
        {
            CreteRecord.IsSelected = true;
        }

        private void MetroExpander_Click_13(object sender, EventArgs e)
        {
            ModifyRecord.IsSelected = true;
        }
        #endregion

        private void MetroButton_Click_22(object sender, RoutedEventArgs e)
        {
            Deliver_SOrder_Id.Text = "";
            Deliver_SCustomer_Id.Text = "";
        }

        private void MetroButton_Click_23(object sender, RoutedEventArgs e)
        {
            Deliver_Place_Of_Delivery.Text = "";
            Deliver_Destination.Text = "";
            Deliver_Goods.Text = "";
            Deliver_DateTime_Start.Text = "";
            Deliver_DateTime_End.Text = "";
        }

        private void MetroButton_Click_24(object sender, RoutedEventArgs e)
        {
            Deliver_IOrder_Id.Text = "";
            IDeliver_DateTime.Text = "";
            Deliver_ICustomer_Id.Text = "";
            Deliver_ICustomer_Name.Text = "";
            Deliver_ICustomer_Tel.Text = "";
            Deliver_IPlace_Of_Delivery.Text = "";
            Deliver_IDestination.Text = "";
            Deliver_IGoods.Text = "";
            Deliver_INumber.Text = "";
        }

        private void MetroButton_Click_25(object sender, RoutedEventArgs e)
        {
            Deliver_UOrder_Id.Text = "";
            UDeliver_DateTime.Text = "";
            Deliver_UCustomer_Id.Text = "";
            Deliver_UCustomer_Name.Text = "";
            Deliver_UCustomer_Tel.Text = "";
            Deliver_UPlace_Of_Delivery.Text = "";
            Deliver_UDestination.Text = "";
            Deliver_UGoods.Text = "";
            Deliver_UNumber.Text = "";
        }
        //发货准确查询
        private void Deliver_SExactly_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = DeliverRecord.Deliver_SelectExactly(this);
            SDataShow3.ItemsSource = S.DefaultView;
        }
        //发货条件查询
        private void Deliver_SelectByCondition_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable S = DeliverRecord.Deliver_SelectByCondition(this);
            SDataShow3.ItemsSource = S.DefaultView;
        }
        //发货记录插入
        private void Deliver_Insert_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            DeliverRecord.Deliver_Insert(this);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("DeliverRecord", "Order_Id", this.DeliverRecord_IPageNumber);
            IDataShow3.ItemsSource = DeliverRecord_TableHeadHandle(s).DefaultView;
        }
        //发货记录修改
        private void Deliver_Update_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            DeliverRecord.Deliver_Update(this);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("DeliverRecord", "Order_Id", this.UpdataRecord_IPageNumber);
            UDataShow3.ItemsSource = DeliverRecord_TableHeadHandle(s).DefaultView;
        }
        //发货记录跳页  只有这里有调用 其他不想做
        private void DeliverRecor_SkipPage_Click(object sender, RoutedEventArgs e)
        {
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("DeliverRecord", "Order_Id",this.DeliverRecord_IPageNumber);
            IDataShow3.ItemsSource= Stock_TableHeadHandle(s).DefaultView;
        }
        
        private void MetroButton_Click_26(object sender, RoutedEventArgs e)
        {
            ICustomerId.Text = "";
            ICustomerName.Text = "";
            ICustomerSex.Text = "";
            ICustomerTel.Text = "";
            IEmployee_Id.Text = "";
        }

        private void MetroExpander_Click_14(object sender, EventArgs e)
        {
            CustomerI.IsSelected = true;
        }
        //客户信息添加
        private void Customer_Insert_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            CustomerManagement.Customer_Create(this);
            //刷新视图
            System.Data.DataTable s = Bridge.UsuallyRefreshSkipPage("Customer", "Customer_Id", this.CustormerCreate_PageNumber);
            IDataShow_Customer.ItemsSource = Custormer_TableHeadHandle(s).DefaultView;
        }

        private void MetroExpander_Click_15(object sender, EventArgs e)
        {
            Cstm_DataAnalysis.IsSelected = true;
        }
        //库存查询打印
        private void SSMetroButton_Print_Click(object sender, RoutedEventArgs e)
        {
            //string fileName = "";
            string saveFileName = "";
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xlsx";
                saveDialog.Filter = "Excel 文件|*.xlsx";
               // saveDialog.FileName = fileName;
                saveDialog.ShowDialog();
                saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0) return;  //被点了取消
                Excel.Application xlApp = new Excel.Application();
                if (xlApp == null)
                {
                    System.Windows.MessageBox.Show("无法创建Excel对象，您可能未安装WPS");
                    return;
                }
                Excel.Workbooks workbooks = xlApp.Workbooks;
                Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1]; //取得sheet1

            //Dim app As Excel.Application;
            //Dim book As Excel.Workbook;
            //Dim sheet As Excel.Worksheet;
            //Dim sheet2 As Excel.Worksheet;
            //Dim range As Excel.Range;

            //app = New Excel.Application;
            //book = app.Workbooks.Add();


            //写入行
            DataView view = SDataShow.ItemsSource as DataView;
            System.Data.DataTable dataTable = view.Table;
            for (int i = 0; i < SDataShow.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = SDataShow.Columns[i].Header;
            }
            for (int r = 0; r < SDataShow.Items.Count; r++)
                {
                    for (int i = 0; i < SDataShow.Columns.Count; i++)
                    {

                    worksheet.Cells[r + 2, i + 1] = dataTable.Rows[r][i];//(SDataShow.Columns[i].GetCellContent(SDataShow.Items[r]) as TextBlock).Text;   //读取DataGrid某一行某一列的信息内容，与DataGridView不同的地方
                }
                    //System.Windows.Forms.Application.DoEvents();实时更新画面
                }
                worksheet.Columns.EntireColumn.AutoFit();
                MessageBox.Show(saveFileName + "保存成功");
                if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;
                        workbook.SaveCopyAs(saveFileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("导出文件可能正在被打断!" + ex.Message);
                    }

                }
                xlApp.Quit();
                GC.Collect();
            

        }


        #region 客户分析变量及方法
        /// <summary>
        /// 随机数
        /// </summary>
        private Random _random = new Random();

        /// <summary>
        /// 图表的尺寸
        /// </summary>
        private double _chartSize = 200;

        /// <summary>
        /// 圆弧的宽度
        /// </summary>
        private double _arcThickness = 40;

        /// <summary>
        /// popup的宽度
        /// </summary>
        private double _popupWidth = 88;

        /// <summary>
        /// popup的高度
        /// </summary>
        private double _popupHeight = 66;
        /// <summary>
        /// 生成图表项 并添加到页面
        /// </summary>
        /// <param name="data">数据</param>

        public double[] purchasingPower = new double[4];
        SolidColorBrush[] brushes = new SolidColorBrush[4];
        private void GenerateItem(double[] data)
        {
            /*
             * 圆弧首尾相连 上个圆弧的终点是下个圆弧的起点
             * 每个圆弧都绑定一个popup 用于显示明细
             * popup内包含一个椭圆背景 一个text 一个折线的虚线
             */

            //下一个圆弧的起点
            double globalStart = 0;
            for (int i = 0; i < data.Length; i++)
            {
                //圆弧的起始角度
                double startAngle = globalStart;
                //圆弧的终结角度
                double endAngle = startAngle + data[i] * 3.6;
                //圆弧的中间点的角度
                double middleAngle = globalStart + data[i] * 3.6 / 2;
                //圆弧和明细背景的颜色
               SolidColorBrush brush = new SolidColorBrush(Color.FromRgb((byte)_random.Next(0, 256), (byte)_random.Next(0, 256), (byte)_random.Next(0, 256)));
                brushes[i] = brush;
                #region arc
                Arc arc = new Arc()
                {
                    ArcThickness = _arcThickness,
                    Stretch = Stretch.None,
                    Fill = brush,
                    StartAngle = startAngle,
                    EndAngle = endAngle
                };
                globalStart = endAngle;
                chartLayout.Children.Add(arc);
                #endregion

                #region popup
                //显示的明细 椭圆为背景+text 放到一个grid容器里
                TextBlock tb = new TextBlock() { Text = string.Format("{0}%", data[i].ToString("0.00")), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
                Ellipse ell = new Ellipse() { Fill = brush };
                //中间点角度小于180 明细靠右显示 否则靠作显示
                Grid detailGrid = new Grid() { Width = _popupHeight, HorizontalAlignment = HorizontalAlignment.Right };
                if (middleAngle > 180)
                {
                    detailGrid.HorizontalAlignment = HorizontalAlignment.Left;
                }
                detailGrid.Children.Add(ell);
                detailGrid.Children.Add(tb);

                //标记线
                Polyline pLine = GetPopupPolyline(middleAngle);
                //popup布局容器
                Grid popupLayout = new Grid();
                popupLayout.Children.Add(pLine);
                popupLayout.Children.Add(detailGrid);
                //popup
                Popup popup = GetPopup(middleAngle);
                popup.Child = popupLayout;
                //将popup的IsOpen绑定到arc的IsMouseOver 也就是鼠标进入arc时 popup就打开
                Binding binding = new Binding()
                {
                    Source = arc,
                    Path = new PropertyPath(Arc.IsMouseOverProperty),
                    Mode = BindingMode.OneWay
                };
                BindingOperations.SetBinding(popup, Popup.IsOpenProperty, binding);

                chartLayout.Children.Add(popup);
                #endregion
            }

            //中间内容
            TextBlock textBlock = new TextBlock();
            textBlock.FontSize = 15;
            textBlock.Width = 100;
            textBlock.Height = 20;
            //SolidColorBrush textBrush = new SolidColorBrush(Color.FromRgb((byte)_random.Next(0, 256), (byte)_random.Next(0, 256), (byte)_random.Next(0, 256)));
            textBlock.Foreground = brushes[0];
            textBlock.Text = "忠诚:99/"+ Math.Round(purchasingPower[0], 2).ToString();
            textBlock.Margin = new Thickness(5, 50, 0, 0);
            chartLayout.Children.Add(textBlock);
            TextBlock textBlock1 = new TextBlock();
            textBlock1.FontSize = 15;
            textBlock1.Width = 100;
            textBlock1.Height = 20;
            //SolidColorBrush textBrush1 = new SolidColorBrush(Color.FromRgb((byte)_random.Next(0, 256), (byte)_random.Next(0, 256), (byte)_random.Next(0, 256)));
            textBlock1.Foreground = brushes[2];
            textBlock1.Text = "信赖:99/" + Math.Round(purchasingPower[2], 2).ToString();
            textBlock1.Margin = new Thickness(5, 10, 0, 0);
            chartLayout.Children.Add(textBlock1);
            TextBlock textBlock2 = new TextBlock();
            textBlock2.FontSize = 15;
            textBlock2.Width = 100;
            textBlock2.Height = 20;
            //SolidColorBrush textBrush2 = new SolidColorBrush(Color.FromRgb((byte)_random.Next(0, 256), (byte)_random.Next(0, 256), (byte)_random.Next(0, 256)));
            textBlock2.Foreground = brushes[1];
            textBlock2.Text = "依赖:99/" + Math.Round(purchasingPower[1], 2).ToString();
            textBlock2.Margin = new Thickness(5, -30, 0, 0);
            chartLayout.Children.Add(textBlock2);
            TextBlock textBlock3 = new TextBlock();
            textBlock3.FontSize = 15;
            textBlock3.Width = 100;
            textBlock3.Height = 20;
           // SolidColorBrush textBrush3 = new SolidColorBrush(Color.FromRgb((byte)_random.Next(0, 256), (byte)_random.Next(0, 256), (byte)_random.Next(0, 256)));
            textBlock3.Foreground = brushes[3];
            textBlock3.Text = "需求:99/" + Math.Round(purchasingPower[3], 2).ToString();
            textBlock3.Margin = new Thickness(5, -70, 0, 0);
            chartLayout.Children.Add(textBlock3);
        }

        /// <summary>
        /// 获取popup内的标记线
        /// </summary>
        /// <param name="middleAngle">圆弧中间点的角度</param>
        /// <returns>Polyline</returns>
        private Polyline GetPopupPolyline(double middleAngle)
        {
            Polyline pLine = new Polyline() { Stroke = new SolidColorBrush(Color.FromRgb(0, 0, 0)), StrokeDashArray = new DoubleCollection(new double[] { 5, 2 }) };
            double x1 = 0, y1 = 0;
            double x2 = 0, y2 = 0;
            double x3 = 0, y3 = 0;
            if (middleAngle > 0 && middleAngle <= 90)
            {
                x1 = 0; y1 = _popupHeight;
                x2 = _popupWidth / 2; y2 = _popupHeight;
                x3 = _popupWidth * 3 / 4; y3 = _popupHeight / 2;
            }
            if (middleAngle > 90 && middleAngle <= 180)
            {
                x1 = 0; y1 = 0;
                x2 = _popupWidth / 2; y2 = 0;
                x3 = _popupWidth * 3 / 4; y3 = _popupHeight / 2;
            }
            if (middleAngle > 180 && middleAngle <= 270)
            {
                x1 = _popupWidth; y1 = 0;
                x2 = _popupWidth / 2; y2 = 0;
                x3 = _popupWidth / 4; y3 = _popupHeight / 2;
            }
            if (middleAngle > 270 && middleAngle <= 360)
            {
                x1 = _popupWidth; y1 = _popupHeight;
                x2 = _popupWidth / 2; y2 = _popupHeight;
                x3 = _popupWidth / 4; y3 = _popupHeight / 2;
            }
            pLine.Points.Add(new System.Windows.Point(x1, y1));
            pLine.Points.Add(new System.Windows.Point(x2, y2));
            pLine.Points.Add(new System.Windows.Point(x3, y3));
            return pLine;
        }

        /// <summary>
        /// 获取popup
        /// </summary>
        /// <param name="middleAngle">圆弧中间点的角度</param>
        /// <returns>Popup</returns>
        private Popup GetPopup(double middleAngle)
        {
            /*
             * 生成popup
             * 设置popup的offset 让标记线的起点 对应到圆弧的中间点
             */
            Popup popup = new Popup() { Width = _popupWidth, Height = _popupHeight, AllowsTransparency = true, IsHitTestVisible = false };
            //直角三角形 a=r*sinA 勾股定理 c^2=a^2+b^2 b=Sqrt(c^2-a^2)
            double r = _chartSize / 2 - _arcThickness / 2;
            double offsetX = 0, offsetY = 0;
            if (middleAngle > 0 && middleAngle <= 90)
            {
                double sinA = Math.Sin(Math.PI * (90 - middleAngle) / 180);
                double a = r * sinA;
                double c = r;
                double b = Math.Sqrt(c * c - a * a);
                offsetX = _chartSize / 2 + b;
                offsetY = -(_chartSize / 2 + _popupHeight + a);
            }
            if (middleAngle > 90 && middleAngle <= 180)
            {
                double sinA = Math.Sin(Math.PI * (180 - middleAngle) / 180);
                double a = r * sinA;
                double c = r;
                double b = Math.Sqrt(c * c - a * a);
                offsetX = _chartSize / 2 + a;
                offsetY = -(_arcThickness / 2 + (r - b));
            }
            if (middleAngle > 180 && middleAngle <= 270)
            {
                double sinA = Math.Sin(Math.PI * (270 - middleAngle) / 180);
                double a = r * sinA;
                double c = r;
                double b = Math.Sqrt(c * c - a * a);
                offsetX = -_popupWidth + (r - b) + _arcThickness / 2;
                offsetY = -(_arcThickness / 2 + (r - a));
            }
            if (middleAngle > 270 && middleAngle <= 360)
            {
                double sinA = Math.Sin(Math.PI * (360 - middleAngle) / 180);
                double a = r * sinA;
                double c = r;
                double b = Math.Sqrt(c * c - a * a);
                offsetX = -_popupWidth + (r - a) + _arcThickness / 2;
                offsetY = -(_chartSize / 2 + _popupHeight + b);
            }
            popup.HorizontalOffset = offsetX;
            popup.VerticalOffset = offsetY;

            return popup;
        }
        #endregion
        //客户分析点击按钮
        private void MetroButton_CustomerAnalysis_Click(object sender, RoutedEventArgs e)
        {
            //清除避免重叠
            chartLayout.Children.Clear();
            string customer_Analysis_Id = Customer_Analysis_Id.Text;
            double[] values = new double[4];
            //获取忠诚值
            double loyal = CustomerAnalysis.GetLoyalById(customer_Analysis_Id);
            //获取依赖值
            double dependent = CustomerAnalysis.GetDependentById(customer_Analysis_Id);
            //获取信赖值
            double trust =  CustomerAnalysis.GetTrustById(customer_Analysis_Id);
            //获取需求值
            double demand = CustomerAnalysis.GetDemandById(customer_Analysis_Id);
            //购买力总分
            double count = loyal + dependent + trust + demand; ;
            values[0] = loyal/count*100;
            values[1] = dependent/count*100;
            values[2] = trust / count * 100;
            values[3] =demand / count * 100;
            purchasingPower = values;
            double chartSize = 200;
                this._chartSize = chartSize;
                this.chartLayout.Width = this._chartSize;
                this.chartLayout.Height = this._chartSize;
            double arcThickness = 20;
                this._arcThickness = arcThickness;
            GenerateItem(values);
        }
        private void Socket_Server_Click(object sender, EventArgs e)
        {
            FormServer server = new FormServer(); ;
            server.Show();
        }
        int index = 0;
        private void Socket_Client_Click(object sender, EventArgs e)
        {
            string[] users = new string[5];
            users[0] = "仓管老黄";
            users[1] = "客服黄姐";
            users[2] = "业务员黄叔";
            users[3] = "管理员黄哥";
            users[4] = "运输业阿黄";
            string user = users[index % 6];
            index++;
            Form1 client = new Form1(user);
            client.Show();
          
        }
        //报表打印预览
        private void PrintPreview_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            CustomerReport rpt = new CustomerReport();
            rpt.ShowDialog();
        }
        //报表直接打印
        private void PrintDirect_MetroButton_Click(object sender, RoutedEventArgs e)
        {
            RDLCPrinter.ReportViewer rvDoc = new RDLCPrinter.ReportViewer();
            System.Data.DataTable dt2 = new System.Data.DataTable();
            dt2.Columns.Add(new DataColumn("warehouseKeeper", typeof(string)));
            dt2.Columns.Add(new DataColumn("outStockTime", typeof(string)));
            dt2.Columns.Add(new DataColumn("transporter", typeof(string)));
            dt2.Columns.Add(new DataColumn("place", typeof(string)));

            DataRow dr2 = dt2.NewRow();
            dr2["warehouseKeeper"] = "模拟仓管";
            dr2["outStockTime"] = DateTime.Now.ToString();
            dr2["transporter"] = "黄槟";
            dr2["place"] = "泉州师范学院软件学院";
            dt2.Rows.Add(dr2);

            ReportDataSource reportDataSource2 = new ReportDataSource();

            reportDataSource2.Name = "DataSet2";
            reportDataSource2.Value = dt2;
            rvDoc.reportViewer1.LocalReport.DataSources.Add(reportDataSource2);

            //rvDoc.reportViewer1
            //rvDoc.reportViewer1.LocalReport.DataSources.Add(reportDataSource2);
            rvDoc.reportViewer1.LocalReport.ReportPath = @"C:\Users\黄燕槟\Desktop\print\RDLC\OutOfStock.rdlc";// @"D:\\Documents\\GitHub\\DEMO\\RDLC\\RDLC\\CustomerReport.rdlc";
                                                                                                            //rvDoc.reportViewer1.RefreshReport();

            /*自动打印*/
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add(new DataColumn("goods_Id", typeof(string)));
            dt.Columns.Add(new DataColumn("goods_Name", typeof(string)));
            dt.Columns.Add(new DataColumn("warehouse_Id", typeof(string)));
            dt.Columns.Add(new DataColumn("date_Of_Manufacture", typeof(string)));
            dt.Columns.Add(new DataColumn("shelf_Life", typeof(string)));

            DataRow dr = dt.NewRow();
            for (int i = 0; i < 10; i++)
            {
                dt.Rows.Add(new string[] { ("模拟id" + i).ToString(), ("模拟货物名" + i).ToString(), ("模拟仓库"+i).ToString(),
                    DateTime.Now.ToString(),"模拟保质期" + i.ToString()});
            }

            ReportDataSource reportDataSource = new ReportDataSource();
            reportDataSource.Name = "DataSet1";
            reportDataSource.Value = dt;
            rvDoc.reportViewer1.LocalReport.DataSources.Add(reportDataSource);

            RDLCPrinter.BillPrint.Run(rvDoc.reportViewer1.LocalReport);
        }
       
        private void MetroExpander_Click_16(object sender, EventArgs e)
        {
            Cstm_DataAnalysis.IsSelected = true;
        }

        private void MetroExpander_Click_17(object sender, EventArgs e)
        {
            Report.IsSelected = true;
        }
        //修改密码
        private void Password_Change_MetroMenuItem_Click(object sender, RoutedEventArgs e)
        {
            ChangePwd changePwd = new ChangePwd();
            changePwd.EmployeeId.Text = Bridge.ID;
            changePwd.EmployeeId.IsEnabled = false;
            changePwd.Show();
        }
        #region 表头处理
        //仓储表头处理
        public System.Data.DataTable Stock_TableHeadHandle(System.Data.DataTable s)
        {
            s.Columns[0].ColumnName = "货物编号";
            s.Columns[1].ColumnName = "货物名";
            s.Columns[2].ColumnName = "仓库号";
            s.Columns[3].ColumnName = "库存";
            s.Columns[4].ColumnName = "生产日期";
            s.Columns[5].ColumnName = "保质期";
            return s;
        }
        //发货记录表头处理
        public System.Data.DataTable DeliverRecord_TableHeadHandle(System.Data.DataTable s)
        {
            s.Columns[0].ColumnName = "订单编号";
            s.Columns[1].ColumnName = "发货时间";
            s.Columns[2].ColumnName = "客户编号";
            s.Columns[3].ColumnName = "客户姓名";
            s.Columns[4].ColumnName = "客户联系方式";
            s.Columns[5].ColumnName = "发货地";
            s.Columns[6].ColumnName = "目的地";
            s.Columns[7].ColumnName = "货物";
            s.Columns[8].ColumnName = "数量";
            return s;
        }
        //运输表头处理
        public System.Data.DataTable Transport_TableHeadHandle(System.Data.DataTable s)
        {
            s.Columns[0].ColumnName = "工具编号";
            s.Columns[1].ColumnName = "工具种类";
            s.Columns[2].ColumnName = "驾驶员";
            s.Columns[3].ColumnName = "是否空闲";
            s.Columns[4].ColumnName = "续航";
            s.Columns[5].ColumnName = "燃料类型";
            s.Columns[6].ColumnName = "载物量";
            return s;
        }
        //订单表头处理
        public System.Data.DataTable Order_TableHeadHandle(System.Data.DataTable s)
        {
            s.Columns[0].ColumnName = "订单编号";
            s.Columns[1].ColumnName = "订单创建时间";
            s.Columns[2].ColumnName = "客户编号";
            s.Columns[3].ColumnName = "客户姓名";
            s.Columns[4].ColumnName = "客户联系方式";
            s.Columns[5].ColumnName = "发货地";
            s.Columns[6].ColumnName = "目的地";
            s.Columns[7].ColumnName = "货物";
            s.Columns[8].ColumnName = "数量";
            s.Columns[8].ColumnName = "订单状态";
            return s;
        }
        //客户管理处理
        public System.Data.DataTable Custormer_TableHeadHandle(System.Data.DataTable s)
        {
            s.Columns[0].ColumnName = "客户号";
            s.Columns[1].ColumnName = "客户姓名";
            s.Columns[2].ColumnName = "客户性别";
            s.Columns[3].ColumnName = "联系方式";
            s.Columns[4].ColumnName = "业务员";
            return s;
        }
        #endregion
        #region 点击传值
        //仓储货物查询视图点击填充数据
        //private void SDataShow_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    DataRowView dr = SDataShow.SelectedItem as DataRowView;
        //    if (dr != null)
        //    {
        //        SGoodsId.Text = dr["货物编码"].ToString();
        //    }
        //}
        //仓储出库下点击传值
        private void ODataShow_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = ODataShow.SelectedItem as DataRowView;
            if (dr != null)
            {
                OGoodsId.Text = dr["货物编码"].ToString();
                OGoodsName.Text = dr["货物名"].ToString();
                OWarehouseId.Text = dr["仓库号"].ToString();
                OStock.Text = dr["库存"].ToString();
                ODateOfManufacture.Text = dr["生产日期"].ToString();
                OShelfLife.Text = dr["保质期"].ToString();
            }
        }
        //添加发货记录点击传值
        private void IDataShow3_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = IDataShow3.SelectedItem as DataRowView;
            if (dr != null)
            {
                Deliver_IOrder_Id.Text = dr["订单编号"].ToString();
                IDeliver_DateTime.Text = dr["发货时间"].ToString();
                Deliver_ICustomer_Id.Text = dr["客户编号"].ToString();
                Deliver_ICustomer_Name.Text = dr["客户姓名"].ToString();
                Deliver_ICustomer_Tel.Text = dr["客户联系方式"].ToString();
                Deliver_IPlace_Of_Delivery.Text = dr["发货地"].ToString();
                Deliver_IDestination.Text = dr["目的地"].ToString();
                Deliver_IGoods.Text = dr["货物"].ToString();
                Deliver_INumber.Text = dr["数量"].ToString();
            }
        }
        //修改发货记录点击传值
        private void UDataShow3_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = UDataShow3.SelectedItem as DataRowView;
            if (dr != null)
            {
                Deliver_UOrder_Id.Text = dr["订单编号"].ToString();
                UDeliver_DateTime.Text = dr["发货时间"].ToString();
                Deliver_UCustomer_Id.Text = dr["客户编号"].ToString();
                Deliver_UCustomer_Name.Text = dr["客户姓名"].ToString();
                Deliver_UCustomer_Tel.Text = dr["客户联系方式"].ToString();
                Deliver_UPlace_Of_Delivery.Text = dr["发货地"].ToString();
                Deliver_UDestination.Text = dr["目的地"].ToString();
                Deliver_UGoods.Text = dr["货物"].ToString();
                Deliver_UNumber.Text = dr["数量"].ToString();
            }
        }
        //客户修改点击传值
        private void UDataShow_Customer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = UDataShow_Customer.SelectedItem as DataRowView;
            if (dr != null)
            {
                UCustomerId.Text = dr["客户号"].ToString();
                UCustomerName.Text = dr["客户姓名"].ToString();
                UCustomerSex.Text = dr["客户性别"].ToString();
                UCustomerTel.Text = dr["联系方式"].ToString();
                UEmployee_Id.Text = dr["业务员"].ToString();
            }
        }
        //客户添加点击传值
        private void IDataShow_Customer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = IDataShow_Customer.SelectedItem as DataRowView;
            if (dr != null)
            {
                ICustomerId.Text = dr["客户号"].ToString();
                ICustomerName.Text = dr["客户姓名"].ToString();
                ICustomerSex.Text = dr["客户性别"].ToString();
                ICustomerTel.Text = dr["联系方式"].ToString();
                IEmployee_Id.Text = dr["业务员"].ToString();
            }
        }
        //运输工具添加点击传值
        private void IDataShow1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = IDataShow1.SelectedItem as DataRowView;
            if (dr != null)
            {
                ITool_Id.Text = dr["工具编号"].ToString();
                ITool_Type.Text = dr["工具种类"].ToString();
                IDriver.Text = dr["驾驶员"].ToString();
                IIs_Free.Text = dr["是否空闲"].ToString()=="true"?"1":"0";
                IEndurance.Text = dr["续航"].ToString();
                IFuel_Type.Text = dr["燃料类型"].ToString();
                IDeadweight.Text = dr["载物量"].ToString();
            }
        }
        //运输工具修改点击传值
        private void UDataShow1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = UDataShow1.SelectedItem as DataRowView;
            if (dr != null)
            {
                UTool_Id.Text = dr["工具编号"].ToString();
                UTool_Type.Text = dr["工具种类"].ToString();
                UDriver.Text = dr["驾驶员"].ToString();
                UIs_Free.Text = dr["是否空闲"].ToString() == "true" ? "1" : "0"; ;
                UEndurance.Text = dr["续航"].ToString();
                UFuel_Type.Text = dr["燃料类型"].ToString();
                UDeadweight.Text = dr["载物量"].ToString();
            }
        }
        //订单添加传值
        private void IDataShow2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = IDataShow2.SelectedItem as DataRowView;
            if (dr != null)
            {
                IOrder_Id.Text = dr["订单编号"].ToString();
                ICreate_DateTime.Text = dr["订单创建时间"].ToString();
                ICustomer_Id.Text = dr["客户编号"].ToString();
                ICustomer_Name.Text = dr["客户姓名"].ToString();
                ICustomer_Tel.Text = dr["客户联系方式"].ToString();
                IPlace_Of_Delivery.Text = dr["发货地"].ToString();
                IDestination.Text = dr["目的地"].ToString();
                IGoods.Text = dr["货物"].ToString();
                INumber.Text = dr["数量"].ToString();
                IOrder_State.Text = dr["订单状态"].ToString();
            }
        }
        //订单修改传值
        private void UDataShow2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView dr = UDataShow2.SelectedItem as DataRowView;
            if (dr != null)
            {
                UOrder_Id.Text = dr["订单编号"].ToString();
                UCreate_DateTime.Text = dr["订单创建时间"].ToString();
                UCustomer_Id.Text = dr["客户编号"].ToString();
                UCustomer_Name.Text = dr["客户姓名"].ToString();
                UCustomer_Tel.Text = dr["客户联系方式"].ToString();
                UPlace_Of_Delivery.Text = dr["发货地"].ToString();
                UDestination.Text = dr["目的地"].ToString();
                UGoods.Text = dr["货物"].ToString();
                UNumber.Text = dr["数量"].ToString();
                UOrder_State.Text = dr["订单状态"].ToString();
            }
        }
        #endregion
    }
    //数据挖掘之简版货物类
    public class EasyGoods
    {
        // 保质期
        private double shelfLife;
        public double ShelfLife
        {
            get { return shelfLife; }
            set { shelfLife = value; }
        }
        //库存
        private double stock;
        public double Stock
        {
            get { return stock; }
            set { stock = value; }
        }
        //采取策略
        private string strategy;
        public string Strategy
        {
            get { return strategy; }
            set { strategy = value; }
        }
    }
    //数据挖掘之KNN算法类
    public class KNN
    {
        /// <summary>
        /// 样本数据
        /// </summary>
        private List<EasyGoods> sampleList;

        /// <summary>
        /// 未分类数据
        /// </summary>
        private List<EasyGoods> unclassifyList;

        /// <summary>
        /// K值
        /// </summary>
        private int k;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sampleList">样本数据</param>
        /// <param name="unclassifyList">未分类数据</param>
        /// <param name="k">k值</param>
        public KNN(List<EasyGoods> sampleList, List<EasyGoods> unclassifyList, int k)
        {
            this.sampleList = sampleList;
            this.unclassifyList = unclassifyList;
            this.k = k;

        }

        /// <summary>
        /// 分类
        /// </summary>
        public void Classify()
        {
            int sampleCount = sampleList.Count;
            int unclassifyCount = unclassifyList.Count;

            // 
            for (int i = 0; i < unclassifyCount; i++)
            {
                Tuple<string, double>[] tupleArray = new Tuple<string, double>[sampleCount];
                for (int j = 0; j < sampleCount; j++)
                {
                    double distance = CalculateDistance(sampleList[j], unclassifyList[i]);
                    string species = sampleList[j].Strategy;
                    tupleArray[j] = Tuple.Create(species, distance);
                }

                //
                IEnumerable<Tuple<string, double>> selector = tupleArray.OrderBy(t => t.Item2).Take(k);
                Dictionary<string, int> dictionary = new Dictionary<string, int>();
                foreach (Tuple<string, double> tuple in selector)
                {
                    if (dictionary.ContainsKey(tuple.Item1))
                    {
                        dictionary[tuple.Item1]++;
                    }
                    else
                    {
                        dictionary.Add(tuple.Item1, 1);
                    }
                }

                // 
                IEnumerable<KeyValuePair<string, int>> keyValuePair = dictionary.OrderByDescending(t => t.Value).Take(1);
                foreach (KeyValuePair<string, int> kvp in keyValuePair)
                {
                    unclassifyList[i].Strategy = kvp.Key;
                }

                // 
                sampleList.Add(unclassifyList[i]);
                sampleCount++;
                Bridge.AnalysisResult = unclassifyList[0].Strategy;
            }

        }

        /// <summary>
        /// 计算距离
        /// </summary>
        /// <param name="sample">样本数据</param>
        /// <param name="unclassify">未分类数据</param>
        /// <returns>两者欧氏距离</returns>
        public double CalculateDistance(EasyGoods sample, EasyGoods unclassify)
        {
            double delta_ShelfLife = unclassify.ShelfLife - sample.ShelfLife;
            double delta_Stock = unclassify.Stock - sample.Stock;
            return Math.Sqrt(delta_ShelfLife * delta_ShelfLife + delta_Stock * delta_Stock);
        }

        /// <summary>
        /// 打印 还没用
        /// </summary>
        public void Print(string filePath)
        {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < sampleList.Count; i++)
            {
                EasyGoods easyGoods = sampleList[i];
                stringBuilder.AppendLine(i.ToString() + "\t" + easyGoods.ShelfLife.ToString() + "\t" + easyGoods.Stock.ToString()+ "\t" + easyGoods.Strategy);
            }

            System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
            sw.Write(stringBuilder.ToString());
            sw.Flush();
            sw.Close();
            fs.Close();
            fs.Dispose();
        }

    }
}